const Service = require('egg').Service;

// const mock = require('mockjs')
// const { list } = mock.mock({
//     'list|4-6': [{
//         title: '@ctitle',
//         name:'@cname',
//         time:'@datetime'
//     }]
// })

class HomeService extends Service {
    async getNews() {
        const { ctx, app } = this

        // list.forEach(item => {
        //     this.app.mysql.insert('news', item)
        // })

        const { id, keyword, pageIndex, pageSize } = ctx.query;
        let sql = `select * from news where 1=1 `
        let sqlCount = `select count(id) as total from news where 1=1 `
        if (id) {
            sql += `and id=${id} `
            sqlCount += `and id=${id} `
        }
        if (keyword) {
            sql += `and title like "%${keyword}%" `
            sqlCount += `and title like "%${keyword}%" `
        }
        if (pageIndex && pageSize) {
            sql += `limit ${(pageIndex - 1) * pageSize},${pageSize} `
        }
        const data = await app.mysql.query(sql)
        const [{ total }] = await app.mysql.query(sqlCount)
        // return data
        return {
            total,
            data
        }
    }

    /// 添加资讯数据
    async addNews() {
        const { ctx, app } = this
        let { title, name, time } = ctx.request.body
        const data = await app.mysql.insert('news', { title, name, time })
        return data
    }

    /// 编辑资讯数据
    async editNews() {
        const { ctx, app } = this
        const {id}=ctx.request.body
        const data=await this.app.mysql.update('news',{...ctx.request.body,id})
        // const { id, title, name, time } = ctx.request.body
        // const row = {
        //     title, name, time
        // }
        // const options = {
        //     where: {
        //         id
        //     }
        // }
        // console.log(ctx.request.body);
        // const data = await this.app.mysql.update('news', row, options); // 更新 posts 表中的记录
        return data
    }

    /// 删除资讯数据
    async delNews() {
        const { ctx, app } = this
        const data = await app.mysql.delete('news', { id: ctx.params.id })
        return data
    }

}

module.exports = HomeService;